﻿using System;
using System.Collections.Generic;
using System.Text;
using AhpilyServer;
using Island;

namespace Server
{
    public class LoginHandler : IHandler
    {
        Random rand = new Random();

        public void RegisterHandler(HandlerCenter center)
        {
            center.AddHandler(Protocol.ReqLogin, OnLogin);
            center.AddHandler(Protocol.RspLogoff, OnLogoff);
        }

        private void OnLogin(ClientPeer token, byte[] data)
        {
            PBAccount local = Util.Deserilize<PBAccount>(data);

            var has = AccountCache.Instance.GetActor(local.id);
            if(has == null)
            {
                //1.登录成功
                AccountCache.Instance.AddActor(local, token);
                ServerManager.SendClient(token, Protocol.ReqLogin, local);

                //2.通知其他玩家
                ServerManager.SendOther(token, Protocol.RspOtherLogin, local);

                //3.同步其他玩家位置
                var actors = AccountCache.Instance.GetAllActors();
                PBAccounts others = new PBAccounts();
                foreach (var actor in actors)
                {
                    if (actor.id != local.id)
                    {
                        Account account = AccountCache.Instance.GetAccount(actor.id);
                        others.array.Add(account.ToPB());
                    }
                }
                ////测试数据
                //for (int i = 0; i < 5; i++)
                //{
                //    PBAccount p1 = new PBAccount();
                //    p1.id = "nick" + i;
                //    p1.sex = 0;
                //    others.array.Add(p1);
                //}
                if(others.array.Count>0)
                {
                    ServerManager.SendClient(token, Protocol.RspAsycOthers, others);
                }
            }
        }


        private void OnLogoff(ClientPeer token, byte[] data)
        {
            if(token.id != null)
            {
                PBAccount pb = new PBAccount();
                pb.id = token.id;
                ServerManager.SendOther(token, Protocol.RspLogoff, pb);//广播离线
                AccountCache.Instance.DelActor(token);
            }
        }

    }
}
